package org.hongqi.common.senpec.sys.operate;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hongqi.common.senpec.base.mybatisplus.IBaseServiceImpl;
import org.hongqi.common.senpec.base.sevlet.Result;
import org.hongqi.common.senpec.base.spring.security.SpringSecurityUtil;
import org.hongqi.common.senpec.base.utils.ObjectsUtil;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class OperateServiceImpl extends IBaseServiceImpl<OperateMapper, Operate> implements OperateService {

    private final OperateMapper operateMapper;

    @Override
    public Result<Operate> mySave(Operate entity) {
        operateMapper.insert(entity);
        return Result.ok(operateMapper.selectById(entity));
    }

    @Override
    public Result<Operate> mySave(HttpServletRequest request) {
        Operate operate = Operate.builder()//
                .username("")//
                .requestUri(request.getRequestURI())//
                .scheme(request.getScheme())//
                .serverPort(request.getServerPort())//
                .serverName(request.getServerName())//
                .remoteHost(request.getRemoteHost())//
                .remoteAddr(request.getRemoteAddr())//
                .method(request.getMethod())//
                .username(SpringSecurityUtil.getUsername())//
                //
                .build();
        operateMapper.insert(operate);
        return Result.ok(operateMapper.selectById(operate));
    }

    @Override
    public Result<IPage<Operate>> myListObjsWithPage(Operate entity) {
        IPage<Operate> iPage = new Page<>(entity.getCurrent(), entity.getSize());
        LambdaQueryWrapper<Operate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(ObjectsUtil.noNullAndEmpty(entity.getMethod()), Operate::getMethod, entity.getMethod());
        lambdaQueryWrapper.orderByDesc(Operate::getId);
        IPage<Operate> page = operateMapper.selectPage(iPage, lambdaQueryWrapper);
        return Result.ok(page);
    }
}
